package com.geeguo.ebuilder.client.base.tenant.interceptor;

import com.geeguo.ebuilder.client.base.security.model.LoginUser;
import com.geeguo.ebuilder.client.base.security.utils.AuthUtils;
import com.geeguo.ebuilder.client.base.tenant.model.DataContext;
import com.geeguo.ebuilder.client.base.tenant.provider.TenantProvider;
import com.geeguo.ebuilder.client.base.tenant.utils.DataContextHolder;
import com.geeguo.ebuilder.core.common.exception.FrameworkException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

public class TenantInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        DataContext dataContext = TenantProvider.getDataContext();
        if (dataContext == null) {
            throw new FrameworkException("租户编码不合法，无法获取数据访问上下文对象。");
        }
        LoginUser loginUser = AuthUtils.getLoginUser();
        if (loginUser != null && !dataContext.getTenantCode().equals(loginUser.getTenantCode())) {
            throw new FrameworkException("租户编码与用户租户编码不匹配，越权访问。");
        }
        DataContextHolder.setDataContext(dataContext);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DataContextHolder.clearDataContext();
    }
}